package dao.impl;

import dao.ProfilePhotoDao;
import domain.ProfilePhoto;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import utils.JDBCUtils;
import utils.LyyLogUtil;

public class ProfilePhotoDaoImpl implements ProfilePhotoDao {
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public boolean addPhoto(ProfilePhoto profilePhoto) throws Exception {
        String pictureStr=profilePhoto.getPictureStr();
        int userId=profilePhoto.getUserId();
        String sql0="select * from profile_photo where pictureStr=? and userId=? order by uploadTime desc limit 1";

        ProfilePhoto photo = null;
        try {
            photo = template.queryForObject(sql0, new BeanPropertyRowMapper<ProfilePhoto>(ProfilePhoto.class), pictureStr, userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(photo!=null){
            LyyLogUtil.logD("添加失败，该用户已经使用此张头像。");
            return true;
        }

        String sql="insert into profile_photo values(?,?,?,?)";
        int update;
        try {
            update = template.update(sql, null, profilePhoto.getUserId(), profilePhoto.getPictureStr(), profilePhoto.getUploadTime());
        } catch (Exception e) {
            LyyLogUtil.logeE(e.getMessage());
            throw e;
        }
        return update!=0;
    }

    @Override
    public ProfilePhoto findNewestPhoto(String userId) throws Exception {
        String sql="select * from profile_photo where userId=? order by uploadTime desc limit 1";
        ProfilePhoto profilePhoto=null;
        try {
            profilePhoto = template.queryForObject(sql, new BeanPropertyRowMapper<ProfilePhoto>(ProfilePhoto.class), userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return profilePhoto;
    }
}
